package com.pand.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by lh on 2017/10/30.
 */
public class NettyServer {

    @Value("${netty.port}")
    private Integer port;

    private static ChannelFuture channelFuture;
    private static EventLoopGroup bossGroup;
    private static EventLoopGroup workerGroup;
    public static Map<String, Channel> channelMap = new HashMap<>(1);

    public NettyServer(Integer port) {
        this.port = port;
    }

    public NettyServer() {
    }

    public void init() throws Exception {
        //EventLoopGroup是用来处理IO操作的多线程事件循环器
        //bossGroup 用来接收进来的连接
        bossGroup = new NioEventLoopGroup();
        //workerGroup 用来处理已经被接收的连接
        workerGroup = new NioEventLoopGroup();
        try {
            //启动 NIO 服务的辅助启动类
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    //配置 Channel
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            // 注册handler
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            // 绑定端口，开始接收进来的连接
            channelFuture = b.bind(port).sync();
            // 等待服务器 socket 关闭 。
            channelFuture.channel().closeFuture().addListener(remover);
        } finally {
//            workerGroup.shutdownGracefully();
//            bossGroup.shutdownGracefully();
        }
    }

    private final ChannelFutureListener remover = new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            future.channel().close();
        }
    };

    public static void shutdown() {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

    public static void sendMsg(String msg) {
        msg += "$_";
        for (Channel channel : NettyServer.channelMap.values()) {
            if (channel.isActive()) {
                ByteBuf byteBuf = Unpooled.buffer(4 * msg.length());
                byteBuf.writeBytes(msg.getBytes());
                channel.writeAndFlush(byteBuf);
            }else {
                NettyServer.channelMap.remove(channel.id().asShortText());
            }
        }
    }

    public static ChannelFuture getChannelFuture() {
        return channelFuture;
    }

}
